import 'package:flutter/material.dart';
import 'package:sample2/helper/chat_helper.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:sample2/model/chat/chat_user.dart';
import 'package:sample2/pages/chat/anonymous/anonymous_chat_item.dart';
import 'package:sample2/services/chat_service.dart';

class AnonymousChatList extends StatefulWidget {
  const AnonymousChatList({super.key});

  @override
  State<StatefulWidget> createState() {
    return AnonymousChatListState();
  }
}

class AnonymousChatListState extends State {
  List<ChatMessageUser> _users = [];
  int? newMsgHandler;
  @override
  void initState() {
    super.initState();
    ChatHelper.addChangeUserListener(() {
      updateUsers();
    });
    newMsgHandler = ChatHelper.addNewMessageListener((p0) {
      updateUsers();
    });
    ChatService.getChatUsers()?.then((users) {
      ChatHelper.updateUsers(users);
      updateUsers();
    }).catchError((err){
      debugPrint(err.toString());
    });
  }

  void updateUsers(){
    if(mounted){
        setState(() {
          _users = ChatHelper.getUsers();
        });
      }
  }

  @override
  void dispose() {
    ChatHelper.removeNewMessageListener(newMsgHandler);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context)!.anonymous),
      ),
      body: ListView.separated(
        itemCount: _users.length,
        itemBuilder: (BuildContext context, index) {
          ChatMessageUser user = _users[index];
          return AnonymousChatItem(
            user: user,
          );
        },
        separatorBuilder: (context, index) => const Divider(
          height: 1,
          color: Colors.black,
        ),
      ),
    );
  }
}
